<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>空调控制</title>
    <style>
        :root {
            --primary-color: #2196F3;
            --secondary-color: #e0f2f1;
            --text-color: #263238;
            --off-color: #f44336;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --border-radius: 10px;
            --shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
            color: var(--text-color);
        }
        
        .container {
            border-radius: var(--border-radius);
            padding: 20px;
            background-color: white;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        h1, h2 {
            text-align: center;
            color: var(--primary-color);
            margin-bottom: 20px;
            font-weight: 500;
        }
         h3 { /* Added from timer CSS */
            margin-top: 0;
            color: var(--primary-color);
            font-weight: 500;
            font-size: 18px;
        }

        .control-item {
            margin-bottom: 20px;
            padding: 16px;
            background-color: #f9f9f9;
            border-radius: var(--border-radius);
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.2s ease;
        }

        .control-item:hover {
            background-color: var(--secondary-color);
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .control-label {
            font-weight: bold;
            color: var(--primary-color);
            width: 80px; /* Consider adjusting if "重复日期" is too long or use flex-basis */
             min-width: 80px; /* Ensure it doesn't shrink too much */
        }

        .connection-status {
            text-align: center;
            margin-bottom: 20px;
            padding: 10px;
            border-radius: var(--border-radius);
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .connected {
            background-color: #d4edda;
            color: #155724;
        }

        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }

        .connecting {
            background-color: #fff3cd;
            color: #856404;
        }

        button {
            padding: 10px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        button:hover {
            background-color: #1976D2;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        button.off {
            background-color: var(--off-color);
        }

        button.off:hover {
            background-color: #d32f2f;
        }

        .control-buttons {
            display: flex;
            align-items: center;
        }

        .btn-adjust {
            width: 36px;
            height: 36px;
            padding: 0;
            margin: 0 5px;
            font-size: 20px;
            font-weight: bold;
            line-height: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
        }

        input[type="range"] {
            -webkit-appearance: none;
            height: 8px;
            background: #ddd;
            border-radius: 4px;
            width: 120px;
            margin: 0 10px;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 20px;
            height: 20px;
            background: var(--primary-color);
            border-radius: 50%;
            cursor: pointer;
        }

        .value-display {
            margin: 0 10px;
            font-weight: bold;
            min-width: 40px;
            text-align: center;
            color: var(--primary-color);
        }

        .main-switch {
            display: block;
            width: 140px;
            height: 140px;
            margin: 20px auto;
            border-radius: 70px;
            font-size: 18px;
            font-weight: bold;
            box-shadow: 0 6px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .main-switch:hover {
            transform: scale(1.05);
        }

        .main-switch.off:hover {
            transform: scale(1.05);
        }

        /* 模式选择按钮组样式 */
        .mode-buttons {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            width: 100%; /* Ensure it takes available space if control-label is fixed */
            flex-grow: 1; /* Allow mode-buttons to grow */
        }

        .mode-btn {
            flex: 1 0 18%;
            text-align: center;
            padding: 12px 5px;
            border: 2px solid #ddd;
            background-color: white;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: all 0.2s;
            min-width: 60px;
            color: var(--text-color);
        }

        .mode-btn.active {
            border-color: var(--primary-color);
            background-color: var(--primary-color);
            color: white;
        }

        .mode-btn i {
            display: block;
            font-size: 24px;
            margin-bottom: 5px;
        }

        /* 广播消息区域 */
        .broadcast-area {
            background-color: #f1f8e9;
            padding: 15px;
            border-radius: var(--border-radius);
            margin-top: 20px;
            max-height: 120px;
            overflow-y: auto;
        }

        .broadcast-title {
            font-weight: bold;
            color: #33691e;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }

        .broadcast-title i {
            margin-right: 5px;
        }

        .broadcast-message {
            margin-bottom: 5px;
            padding: 5px 0;
            border-bottom: 1px solid #ddd;
            font-size: 13px;
        }
         .broadcast-message:last-child {
            border-bottom: none;
        }

        /* 图标样式 */
        .material-icons {
            font-family: 'Material Icons';
            font-weight: normal;
            font-style: normal;
            font-size: 24px;
            line-height: 1;
            letter-spacing: normal;
            text-transform: none;
            display: inline-block;
            white-space: nowrap;
            word-wrap: normal;
            direction: ltr;
            /* Support for all WebKit browsers. */
            -webkit-font-smoothing: antialiased;
            /* Support for Safari and Chrome. */
            text-rendering: optimizeLegibility;
            /* Support for Firefox. */
            -moz-osx-font-smoothing: grayscale;
            /* Support for IE. */
            font-feature-settings: 'liga';
        }

        /* Styles for Timer Functionality */
        .timer-controls {
            display: flex;
            flex-direction: column; /* Changed to column for better layout on smaller screens potentially */
            gap: 20px;
        }

        /* Desktop layout for timer controls */
        @media (min-width: 600px) {
            .timer-controls {
                flex-direction: row; /* Side-by-side on larger screens */
            }
            .timer-list, .add-timer-section {
                flex: 1;
            }
        }


        .timer-list, .add-timer-section {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: var(--border-radius);
        }

        .timer-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            border-radius: 8px;
            background-color: white;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .timer-info {
            flex-grow: 1;
        }

        .timer-time {
            font-size: 20px;
            font-weight: bold;
            color: var(--primary-color);
        }

        .timer-days {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
            word-break: break-all;
        }

        .timer-type {
            font-weight: bold;
            margin-top: 5px;
            font-size: 14px;
        }

        .timer-type.on {
            color: var(--success-color);
        }

        .timer-type.off {
            color: var(--off-color);
        }

        .timer-actions {
            display: flex;
            gap: 8px;
            align-items: center; /* Vertically align buttons */
        }

        .timer-btn { /* General timer action button (like enable/disable, delete) */
            width: 36px;
            height: 36px;
            border-radius: 50%;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #eee;
            color: #555;
            border: none; /* Ensure no default border */
            cursor: pointer; /* Explicitly set cursor */
        }

        .timer-btn:hover {
            background-color: #ddd;
        }

        .timer-btn.active { /* For enable/disable button when timer is active */
             background-color: var(--primary-color);
             color: white;
        }
        .timer-btn.active:hover {
            background-color: #1976D2;
        }


        .timer-btn.delete {
            background-color: #ffebee;
            color: var(--off-color);
        }

        .timer-btn.delete:hover {
            background-color: #ffcdd2;
        }

        .timer-type-selection {
            display: flex;
            gap: 10px;
            flex-grow: 1; /* Allow to take space */
            justify-content: flex-start;
        }

        .timer-type-btn { /* Specifically for ON/OFF type selection */
            padding: 8px 12px; /* Adjusted padding */
            background-color: #eee;
            color: #555;
            font-size: 14px;
             border: 1px solid #ddd;
        }

        .timer-type-btn.active {
            background-color: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .weekday-buttons {
            display: flex;
            gap: 5px; /* Reduced gap */
            flex-wrap: wrap;
            flex-grow: 1; /* Allow to take space */
             justify-content: flex-start;
        }

        .weekday-btn { /* For day selection */
            width: 32px; /* Slightly smaller */
            height: 32px;
            border-radius: 50%;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #eee;
            color: #555;
            font-size: 13px; /* Adjusted font size */
            border: 1px solid #ddd;
        }

        .weekday-btn.active {
            background-color: var(--primary-color);
            color: white;
             border-color: var(--primary-color);
        }

        .action-btn { /* For "Add Timer" button */
            width: 100%;
            padding: 12px;
            margin-top: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
             background-color: var(--success-color); /* Make it distinct */
        }
        .action-btn:hover {
            background-color: #388E3C; /* Darker green on hover */
        }


        .empty-timer-message {
            text-align: center;
            color: #888;
            padding: 20px;
            font-style: italic;
        }
        input[type="time"] {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ccc;
            flex-grow: 1;
        }

    </style>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1>空调控制</h1>

        <div id="connection-status" class="connection-status disconnected">
            <i class="material-icons">cloud_off</i> 未连接
        </div>

        <button id="main-switch" class="main-switch off">
            <i class="material-icons" style="font-size: 36px;">power_settings_new</i><br>
            电源关闭
        </button>
    </div>

    <div class="container">
        <h2>空调控制面板</h2>
        <div id="ac-controls">
            <div class="control-item">
                <span class="control-label">风速等级:</span>
                <div class="control-buttons">
                    <button class="btn-adjust" id="fan-decrease">-</button>
                    <input type="range" id="fan-control" min="1" max="3" step="1" value="1">
                    <button class="btn-adjust" id="fan-increase">+</button>
                    <span id="fan-display" class="value-display">1级</span>
                </div>
            </div>
            <div class="control-item">
                <span class="control-label">运行模式:</span>
                <div class="mode-buttons">
                    <div class="mode-btn" data-mode="kGreeAuto">
                        <i class="material-icons">settings</i>
                        自动
                    </div>
                    <div class="mode-btn" data-mode="kGreeDry">
                        <i class="material-icons">water_drop</i>
                        除湿
                    </div>
                    <div class="mode-btn" data-mode="kGreeCool">
                        <i class="material-icons">ac_unit</i>
                        制冷
                    </div>
                    <div class="mode-btn" data-mode="kGreeFan">
                        <i class="material-icons">toys</i>
                        送风
                    </div>
                    <div class="mode-btn" data-mode="kGreeHeat">
                        <i class="material-icons">whatshot</i>
                        制热
                    </div>
                </div>
            </div>
            <div class="control-item">
                <span class="control-label">设定温度:</span>
                <div class="control-buttons">
                    <button class="btn-adjust" id="temp-decrease">-</button>
                    <input type="range" id="temp-control" min="16" max="30" step="1" value="25">
                    <button class="btn-adjust" id="temp-increase">+</button>
                    <span id="temp-display" class="value-display">25°C</span>
                </div>
            </div>
            <div class="control-item">
                <span class="control-label">垂直摆风:</span>
                <button id="vf-control">
                    <i class="material-icons">height</i>
                    开启/关闭
                </button>
            </div>
            <div class="control-item">
                <span class="control-label">面板灯光:</span>
                <button id="light-control">
                    <i class="material-icons">lightbulb</i>
                    开启/关闭
                </button>
            </div>
            <div class="control-item">
                <span class="control-label">睡眠模式:</span>
                <button id="sleep-control">
                    <i class="material-icons">hotel</i>
                    开启/关闭
                </button>
            </div>
            <div class="control-item">
                <span class="control-label">强力模式:</span>
                <button id="turbo-control">
                    <i class="material-icons">flash_on</i>
                    开启/关闭
                </button>
            </div>
        </div>
    </div>

    <div class="container">
        <h2>定时设置</h2>
        <div class="timer-controls">
            <div class="timer-list">
                <h3>已设置的定时任务</h3>
                <div id="timer-tasks-container">
                    <div class="empty-timer-message">暂无定时任务</div>
                </div>
            </div>

            <div class="add-timer-section">
                <h3>新增定时任务</h3>
                <div class="control-item">
                    <span class="control-label">定时类型:</span>
                    <div class="timer-type-selection">
                        <button id="timer-on-btn" class="timer-type-btn active">开启</button>
                        <button id="timer-off-btn" class="timer-type-btn">关闭</button>
                    </div>
                </div>

                <div class="control-item">
                    <span class="control-label">定时时间:</span>
                    <input type="time" id="timer-time-input" value="08:00">
                </div>

                <div class="control-item">
                    <span class="control-label">重复日期:</span>
                    <div class="weekday-buttons">
                        <button class="weekday-btn active" data-day="0">日</button>
                        <button class="weekday-btn active" data-day="1">一</button>
                        <button class="weekday-btn active" data-day="2">二</button>
                        <button class="weekday-btn active" data-day="3">三</button>
                        <button class="weekday-btn active" data-day="4">四</button>
                        <button class="weekday-btn active" data-day="5">五</button>
                        <button class="weekday-btn active" data-day="6">六</button>
                    </div>
                </div>

                <button id="add-timer-btn" class="action-btn">
                    <i class="material-icons">add_alarm</i> 添加定时
                </button>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="broadcast-title">
            <i class="material-icons">record_voice_over</i> 服务器广播信息
        </div>
        <div id="broadcast-area" class="broadcast-area">
            <div class="broadcast-message">等待服务器连接...</div>
        </div>
    </div>

    <script>
        // WebSocket连接
        let socket = null;
        const connectionStatus = document.getElementById('connection-status');
        const broadcastArea = document.getElementById('broadcast-area');

        // 显示模式的中文名称
        const modeNames = {
            'kGreeAuto': '自动',
            'kGreeDry': '除湿',
            'kGreeCool': '制冷',
            'kGreeFan': '送风',
            'kGreeHeat': '制热'
        };

        // 保存当前空调状态
        let currentStatus = {};

        // Timer related global variables
        let timerTasks = []; // 存储定时任务
        let currentTimerType = 'on'; // 默认定时类型 for adding new timers
        let selectedDays = [0, 1, 2, 3, 4, 5, 6]; // 默认全选 for adding new timers

        // 添加服务器广播消息
        function addBroadcastMessage(message) {
            const msgElem = document.createElement('div');
            msgElem.className = 'broadcast-message';
            msgElem.textContent = `${new Date().toLocaleTimeString('zh-CN', { hour12: false })}: ${message}`;

            // Prepend new messages
            if (broadcastArea.firstChild) {
                broadcastArea.insertBefore(msgElem, broadcastArea.firstChild);
            } else {
                broadcastArea.appendChild(msgElem);
            }


            // 保持消息数量在合理范围内
            while (broadcastArea.children.length > 20) { // Increased limit a bit
                broadcastArea.removeChild(broadcastArea.lastChild);
            }
        }

        // 连接WebSocket
        function connectWebSocket() {
            const wsUrl = `ws:/服务器IP`;

            connectionStatus.innerHTML = '<i class="material-icons">sync</i> 正在连接...';
            connectionStatus.className = 'connection-status connecting';

            socket = new WebSocket(wsUrl);

            socket.onopen = function(e) {
                console.log('WebSocket连接已建立');
                connectionStatus.innerHTML = '<i class="material-icons">cloud_done</i> 已连接';
                connectionStatus.className = 'connection-status connected';
                addBroadcastMessage("已连接到服务器");

                socket.send('get_status'); // 请求空调状态

                // 连接后请求定时任务列表 (add delay as in user's code)
                setTimeout(() => {
                    requestTimerTasks();
                }, 500); // Reduced delay slightly
            };

            socket.onmessage = function(event) {
                console.log('收到消息:', event.data);
                let messageHandled = false;
                try {
                    const data = JSON.parse(event.data);

                    // 1. Check for timer responses
                    if (data.timer_response) {
                        messageHandled = true;
                        switch (data.timer_response) {
                            case 'timers_list':
                                timerTasks = data.tasks || [];
                                renderTimerTasks();
                                addBroadcastMessage("定时任务列表已更新");
                                break;
                            case 'timer_added':
                                if (data.task) {
                                    // Avoid duplicates if server echoes back on get_timers too soon
                                    if (!timerTasks.find(t => t.id === data.task.id)) {
                                        timerTasks.push(data.task);
                                    }
                                }
                                renderTimerTasks();
                                addBroadcastMessage(`定时任务已添加: ${data.task.time} ${data.task.type === 'on' ? '开启' : '关闭'}`);
                                break;
                            case 'timer_updated':
                                if (data.task) {
                                    const index = timerTasks.findIndex(t => t.id === data.task.id);
                                    if (index !== -1) {
                                        timerTasks[index] = data.task;
                                    } else {
                                        timerTasks.push(data.task); // If not found, add it (server might be source of truth)
                                    }
                                    renderTimerTasks();
                                    addBroadcastMessage(`定时任务已更新: ${data.task.time}`);
                                }
                                break;
                            case 'timer_deleted':
                                if (data.id) {
                                    timerTasks = timerTasks.filter(t => t.id !== data.id);
                                    renderTimerTasks();
                                    addBroadcastMessage(`定时任务已删除: ID ${data.id}`);
                                }
                                break;
                            default:
                                messageHandled = false; // Unknown timer_response
                                addBroadcastMessage(`收到未知定时器响应: ${data.timer_response}`);
                        }
                    }
                    // 2. If not a timer response, check for AC status
                    else if (typeof data.switch !== 'undefined' && typeof data.mode !== 'undefined') {
                        messageHandled = true;
                        currentStatus = data;
                        updateControlsFromStatus(data);
                        updateMainSwitchButton(data.switch);
                        // Avoid redundant status message if it's just an echo of a command
                        // This simple check isn't perfect but can reduce noise
                        if (JSON.stringify(data) !== JSON.stringify(currentStatus)) {
                           // addBroadcastMessage(`收到状态更新: 空调${data.switch ? '开启' : '关闭'}, 模式: ${modeNames[data.mode] || data.mode}, 温度: ${data.temp}°C`);
                        }
                    }

                    if (!messageHandled && event.data) { // Log if JSON but not processed
                        console.warn('收到未处理的JSON消息:', data);
                        addBroadcastMessage(`收到其他JSON数据: ${event.data.substring(0,100)}...`);
                    }

                } catch (e) {
                    console.error('解析或处理消息失败:', e, event.data);
                    addBroadcastMessage(`收到无法解析的消息: ${event.data}`);
                }
            };

            socket.onclose = function(event) {
                connectionStatus.innerHTML = '<i class="material-icons">cloud_off</i> 连接已断开';
                connectionStatus.className = 'connection-status disconnected';
                addBroadcastMessage("与服务器的连接已断开，3秒后尝试重连...");
                setTimeout(connectWebSocket, 3000);
            };

            socket.onerror = function(error) {
                console.error('WebSocket错误:', error);
                connectionStatus.innerHTML = '<i class="material-icons">error</i> 连接错误';
                connectionStatus.className = 'connection-status disconnected';
                addBroadcastMessage("WebSocket连接发生错误");
            };
        }

        // 根据状态更新主开关按钮
        function updateMainSwitchButton(isOn) {
            const mainSwitch = document.getElementById('main-switch');
            if (isOn) {
                mainSwitch.innerHTML = '<i class="material-icons" style="font-size: 36px;">power_settings_new</i><br>电源开启';
                mainSwitch.className = 'main-switch';
            } else {
                mainSwitch.innerHTML = '<i class="material-icons" style="font-size: 36px;">power_settings_new</i><br>电源关闭';
                mainSwitch.className = 'main-switch off';
            }
        }

        // 根据状态设置控制界面
        function updateControlsFromStatus(status) {
            document.getElementById('fan-control').value = status.fan;
            document.getElementById('fan-display').textContent = `${status.fan}级`;

            const modeButtons = document.querySelectorAll('.mode-btn');
            modeButtons.forEach(btn => {
                btn.classList.toggle('active', btn.dataset.mode === status.mode);
            });

            document.getElementById('temp-control').value = status.temp;
            document.getElementById('temp-display').textContent = `${status.temp}°C`;

            const vfControl = document.getElementById('vf-control');
            vfControl.className = status.vf ? '' : 'off';
            vfControl.innerHTML = status.vf ?
                '<i class="material-icons">swap_vert</i> 已开启' : // Changed icon for clarity
                '<i class="material-icons">swap_vert</i> 已关闭';

            const lightControl = document.getElementById('light-control');
            lightControl.className = status.light ? '' : 'off';
            lightControl.innerHTML = status.light ?
                '<i class="material-icons">lightbulb</i> 已开启' :
                '<i class="material-icons">lightbulb_outline</i> 已关闭'; // Changed icon for off state

            const sleepControl = document.getElementById('sleep-control');
            sleepControl.className = status.sleep ? '' : 'off';
            sleepControl.innerHTML = status.sleep ?
                '<i class="material-icons">hotel</i> 已开启' :
                '<i class="material-icons">hotel</i> 已关闭';

            const turboControl = document.getElementById('turbo-control');
            turboControl.className = status.turbo ? '' : 'off';
            turboControl.innerHTML = status.turbo ?
                '<i class="material-icons">flash_on</i> 已开启' :
                '<i class="material-icons">flash_on</i> 已关闭';

            const controls = document.querySelectorAll('#ac-controls input, #ac-controls button, .mode-btn');
            controls.forEach(control => {
                control.disabled = !status.switch;
                if (!status.switch) {
                    control.classList.add('disabled'); // You might need a CSS rule for .disabled
                } else {
                    control.classList.remove('disabled');
                }
            });
             // Disable timer section if AC is off? Or allow setting timers even if AC is off?
            // For now, timer section is independent of AC power state for adding/viewing timers.
            // Actual execution of timers would be handled by the server.
        }

        // 发送控制命令到服务器
        function sendControl(parameter, value) {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const controlMsg = {
                    command: 'set_status',
                    parameter: parameter,
                    value: value
                };
                socket.send(JSON.stringify(controlMsg));
                console.log('发送控制命令:', controlMsg);
                addBroadcastMessage(`发送命令: ${parameter}=${value}`);
            } else {
                addBroadcastMessage("发送命令失败：未连接到服务器");
            }
        }

        // 定时任务功能 JS
        function requestTimerTasks() {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify({ timer_command: 'get_timers' }));
                addBroadcastMessage("请求定时任务列表...");
            }
        }

        function renderTimerTasks() {
            const container = document.getElementById('timer-tasks-container');
            container.innerHTML = ''; // Clear previous tasks

            if (!timerTasks || timerTasks.length === 0) {
                container.innerHTML = '<div class="empty-timer-message">暂无定时任务</div>';
                return;
            }

            timerTasks.sort((a, b) => a.time.localeCompare(b.time)); // Sort by time

            timerTasks.forEach(task => {
                const taskElement = document.createElement('div');
                taskElement.className = 'timer-item';

                const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                const daysList = task.days.map(d => dayNames[d]).join(' ') || '无重复';
                 const typeText = task.type === 'on' ? '开启空调' : '关闭空调';

                taskElement.innerHTML = `
                    <div class="timer-info">
                        <div class="timer-time">${task.time}</div>
                        <div class="timer-days">重复: ${daysList}</div>
                        <div class="timer-type ${task.type}">${typeText}</div>
                    </div>
                    <div class="timer-actions">
                        <button class="timer-btn ${task.enabled ? 'active' : ''}" title="${task.enabled ? '禁用此定时' : '启用此定时'}" data-id="${task.id}" data-action="toggle">
                            <i class="material-icons">${task.enabled ? 'alarm_on' : 'alarm_off'}</i>
                        </button>
                        <button class="timer-btn delete" title="删除定时" data-id="${task.id}" data-action="delete">
                            <i class="material-icons">delete_forever</i>
                        </button>
                    </div>
                `;
                container.appendChild(taskElement);
            });

            document.querySelectorAll('.timer-btn[data-action]').forEach(btn => {
                btn.addEventListener('click', function() {
                    const taskId = this.dataset.id;
                    const action = this.dataset.action;

                    if (!socket || socket.readyState !== WebSocket.OPEN) {
                        addBroadcastMessage("定时操作失败：未连接");
                        return;
                    }

                    if (action === 'delete') {
                        if (confirm(`确定要删除ID为 ${taskId} 的定时任务吗？`)) {
                             socket.send(JSON.stringify({ timer_command: 'delete_timer', id: taskId }));
                        }
                    } else if (action === 'toggle') {
                        const task = timerTasks.find(t => t.id === taskId);
                        if (task) {
                            socket.send(JSON.stringify({
                                timer_command: 'update_timer',
                                id: taskId,
                                enabled: !task.enabled // Send the new desired state for 'enabled'
                            }));
                        }
                    }
                });
            });
        }


        function initControlEvents() {
            document.getElementById('main-switch').addEventListener('click', function() {
                sendControl('switch', !currentStatus.switch);
            });

            const fanControl = document.getElementById('fan-control');
            const fanDisplay = document.getElementById('fan-display');
            fanControl.addEventListener('input', () => fanDisplay.textContent = `${fanControl.value}级`);
            fanControl.addEventListener('change', () => sendControl('fan', parseInt(fanControl.value)));
            document.getElementById('fan-decrease').addEventListener('click', () => {
                if (parseInt(fanControl.value) > fanControl.min) {
                    fanControl.value = parseInt(fanControl.value) - 1;
                    fanDisplay.textContent = `${fanControl.value}级`;
                    sendControl('fan', parseInt(fanControl.value));
                }
            });
            document.getElementById('fan-increase').addEventListener('click', () => {
                 if (parseInt(fanControl.value) < fanControl.max) {
                    fanControl.value = parseInt(fanControl.value) + 1;
                    fanDisplay.textContent = `${fanControl.value}级`;
                    sendControl('fan', parseInt(fanControl.value));
                }
            });

            document.querySelectorAll('.mode-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    if (!this.disabled) sendControl('mode', this.dataset.mode);
                });
            });

            const tempControl = document.getElementById('temp-control');
            const tempDisplay = document.getElementById('temp-display');
            tempControl.addEventListener('input', () => tempDisplay.textContent = `${tempControl.value}°C`);
            tempControl.addEventListener('change', () => sendControl('temp', parseInt(tempControl.value)));
            document.getElementById('temp-decrease').addEventListener('click', () => {
                if (parseInt(tempControl.value) > tempControl.min) {
                    tempControl.value = parseInt(tempControl.value) - 1;
                    tempDisplay.textContent = `${tempControl.value}°C`;
                    sendControl('temp', parseInt(tempControl.value));
                }
            });
            document.getElementById('temp-increase').addEventListener('click', () => {
                if (parseInt(tempControl.value) < tempControl.max) {
                    tempControl.value = parseInt(tempControl.value) + 1;
                    tempDisplay.textContent = `${tempControl.value}°C`;
                    sendControl('temp', parseInt(tempControl.value));
                }
            });

            document.getElementById('vf-control').addEventListener('click', () => sendControl('vf', !currentStatus.vf));
            document.getElementById('light-control').addEventListener('click', () => sendControl('light', !currentStatus.light));
            document.getElementById('sleep-control').addEventListener('click', () => sendControl('sleep', !currentStatus.sleep));
            document.getElementById('turbo-control').addEventListener('click', () => sendControl('turbo', !currentStatus.turbo));
        }

        function initTimerEvents() {
            const timerOnBtn = document.getElementById('timer-on-btn');
            const timerOffBtn = document.getElementById('timer-off-btn');

            timerOnBtn.addEventListener('click', function() {
                currentTimerType = 'on';
                this.classList.add('active');
                timerOffBtn.classList.remove('active');
            });

            timerOffBtn.addEventListener('click', function() {
                currentTimerType = 'off';
                this.classList.add('active');
                timerOnBtn.classList.remove('active');
            });

            document.querySelectorAll('.weekday-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const day = parseInt(this.dataset.day);
                    this.classList.toggle('active');
                    if (this.classList.contains('active')) {
                        if (!selectedDays.includes(day)) selectedDays.push(day);
                    } else {
                        selectedDays = selectedDays.filter(d => d !== day);
                    }
                    selectedDays.sort((a,b) => a - b); // Keep sorted
                    console.log("Selected days:", selectedDays);
                });
            });

            document.getElementById('add-timer-btn').addEventListener('click', function() {
                if (selectedDays.length === 0) {
                    addBroadcastMessage("添加定时失败：请至少选择一个重复日期。");
                    alert("请至少选择一个重复日期。");
                    return;
                }
                const timeValue = document.getElementById('timer-time-input').value;
                if (!timeValue) {
                    addBroadcastMessage("添加定时失败：请选择一个有效的定时时间。");
                    alert("请选择一个有效的定时时间。");
                    return;
                }

                const timerData = {
                    timer_command: 'add_timer',
                    type: currentTimerType,
                    time: timeValue,
                    days: selectedDays,
                    enabled: true // New timers are enabled by default
                };

                if (socket && socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify(timerData));
                    // addBroadcastMessage(`发送添加定时命令: ${currentTimerType === 'on' ? '开启' : '关闭'} at ${timeValue}`);
                     // Don't add message here, wait for server confirmation via 'timer_added'
                } else {
                    addBroadcastMessage("添加定时失败：未连接到服务器。");
                }
            });
        }


        window.addEventListener('load', function() {
            connectWebSocket();
            initControlEvents();
            initTimerEvents(); // Initialize timer event listeners
            addBroadcastMessage("页面已加载，准备连接服务器...");
            renderTimerTasks(); // Initial render (likely empty)
        });

        // 定期请求状态更新 (AC status)
        setInterval(() => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send('get_status');
            }
        }, 10000); // Every 10 seconds for AC status

        // Periodically request timer list updates? Or rely on server push?
        // For now, relying on initial load and updates from add/delete/toggle.
        // If other clients can modify timers, a periodic refresh might be good.
        // setInterval(() => {
        //     requestTimerTasks();
        // }, 60000); // e.g., every minute

    </script>
</body>
</html>